//
//  TableViewBaseCell.swift
//  WanAndroidLearn
//
//  Created by TRS-Mobile on 2023/11/2.
//

import Foundation
import UIKit
import RxSwift
import RxCocoa
import SnapKit
import SwifterSwift
import RxTheme

class TableViewBaseCell: UITableViewCell {
    var disposeBag = DisposeBag()
    var selectionColor: UIColor? {
        didSet {
            setSelected(isSelected, animated: true)
        }
    }
    
    lazy var containerView: UIBaseView = {
        let view = UIBaseView()
        view.backgroundColor = .clear
        view.layerCornerRadius = Configs.BaseDimensions.cornerRadius
        self.addSubview(view)
        view.snp.makeConstraints({ (make) in
            make.edges.equalToSuperview()
                .inset(UIEdgeInsets(horizontal: self.inset, vertical: self.inset/2))
        })
        return view
    }()
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        backgroundColor = selected ? selectionColor : .clear
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        makeUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        makeUI()
    }
    
    func makeUI() {
        layer.masksToBounds = true
        selectionStyle = .none
        backgroundColor = .clear
        theme.selectionColor = themed { $0.primary }
        containerView.theme.backgroundColor = themed { $0.primary }
        updateUI()
    }

    func updateUI() {
        setNeedsDisplay()
    }

//    func bind(to viewModel: TableViewCellViewModel) {
//
//    }
}

extension Reactive where Base: TableViewBaseCell {
    var selectionColor: Binder<UIColor?> {
        return Binder(self.base) { view, attr in
            view.selectionColor = attr
        }
    }
}

extension ThemeProxy where Base: TableViewBaseCell {
    var selectionColor: ThemeAttribute<UIColor?> {
        get { fatalError("set only") }
        set {
            base.selectionColor = newValue.value
            let disposable = newValue.stream
                .take(until: base.rx.deallocating)
                .observe(on: MainScheduler.instance)
                .bind(to: base.rx.selectionColor)
            hold(disposable, for: "selectionColor")
        }
    }
    
}
